package com.xmx.ndmallwxapi.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.map.MapUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import com.xmx.common.utils.R;
import com.xmx.ndmallwxapi.feign.MallFeignClient;
import com.xmx.ndmallwxapi.utils.TencentUtil;
import com.xmx.ndmallwxapi.vo.mall.Storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/wx/storage")
public class FileController {



    @Autowired
    TencentUtil tencentUtil;

    @Autowired
    MallFeignClient mallFeignClient;


    @GetMapping("/download/{key}")
    public void  downfile(HttpServletRequest request, HttpServletResponse response, @PathVariable("key")String key) throws IOException {
        tencentUtil.downfile(request, response, key);
        return ;

    }


    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        R store = tencentUtil.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename);
         return store;
    }

    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key){
        R r = mallFeignClient.findfileBykey(key);
        Storage storage = MapUtil.get(r, "data", Storage.class);
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        String type  = storage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);
        Resource file = tencentUtil.loadPictrue(key);
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }

}
